<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>主播</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h2 style="text-align: center;">这是主播页面</h2>
<input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia()"/>
<input type="button" title="关闭摄像头" value="关闭摄像头" onclick="closeMedia()"/>

<video id="video" width="500px" height="500px" autoplay="autoplay"></video>

<video id="player" width="500px" height="500px"></video>

<button onclick="start()">开始直播</button>
<button onclick="stop()">停止直播</button>
<script>
    var ws = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        connectWebSocket()
    } else {
        alert('Not support websocket')
    }

    function connectWebSocket() {
        ws = new WebSocket("ws://localhost:8081/ws");
    }

    //获得video摄像头区域
    var video = document.getElementById("video");
    var player = document.getElementById("player");

    // 获取设备列表
    navigator.mediaDevices.enumerateDevices().then(deviceList => {
        // audiooutput 扬声器
        // audioinput  麦克风
        // audiooutput 摄像
        console.log(deviceList)
    }).catch(err => console.log(err))

    var promise, stream, options, media, media2, chunks = [], chunks2 = []

    function getMedia() {
        var constraints = {
            video: {width: 500, height: 500},
            audio: true
        };
        /*
        这里介绍新的方法:H5新媒体接口 navigator.mediaDevices.getUserMedia()
        这个方法会提示用户是否允许媒体输入,(媒体输入主要包括相机,视频采集设备,屏幕共享服务,麦克风,A/D转换器等)
        返回的是一个Promise对象。
        如果用户同意使用权限,则会将 MediaStream对象作为resolve()的参数传给then()
        如果用户拒绝使用权限,或者请求的媒体资源不可用,则会将 PermissionDeniedError作为reject()的参数传给catch()
        */
        promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(function (MediaStream) {
            stream = MediaStream
            video.style.display = ''
            video.srcObject = stream;
            video.play();

            options = {// 音频比特率为128kbps,视频比特率为2.5Mbps的媒体录制器
                audioBitsPerSecond: 128000,
                videoBitsPerSecond: 2500000,
            }
            media = new MediaRecorder(stream, options)
            media2 = new MediaRecorder(stream, options)
            media.start()// 开始录制流数据
            media.ondataavailable = function (e) {
                chunks.push(e.data);
            }
            media2.ondataavailable = function (e) {
                chunks2.push(e.data);
            }
            media.onstop = function (e) {
                console.log("data available after MediaRecorder.stop() called.");
                options.mimeType = 'video/mp4'
                debugger
                // 将录制的流转换成 blob ，并且把 blob 放到第二个video标签播放
                var blob = new Blob(chunks, options);
                try {
                    ws.send(blob)
                    /*var reader = new FileReader();
                    reader.addEventListener("loadend", function() {
                        // reader.result 包含被转化为类型数组 typed array 的 blob
                        console.log(reader.result)
                        ws.send(reader.result)
                    });
                    reader.readAsArrayBuffer(blob);*/
                } catch (e) {
                    console.log(e)
                }
                //var audioURL = window.URL.createObjectURL(blob);

                // player.src = audioURL
                // player.play()// 播放录制的视频
                console.log("recorder stopped");
            }

            media2.onstop = function (e) {
                console.log("data available after MediaRecorder.stop() called.");
                options.mimeType = 'video/mp4'
                // 将录制的流转换成 blob ，并且把 blob 放到第二个video标签播放
                var blob = new Blob(chunks2, options);
                try {
                    ws.send(blob)
                } catch (e) {
                    console.log(e)
                }
                console.log("recorder stopped");
            }
            /*setInterval(function (){
                if (media.state=='inactive'){
                    media.start()
                    media2.stop();
                }else {
                    media2.start()
                    media.stop();
                }
            },2000)*/
        }).catch(function (PermissionDeniedError) {
            console.log(PermissionDeniedError);
        })
    }

    function closeMedia() {
        video.style.display = 'none'
        video.pause()
        media.stop()
        // 关闭摄像头
        stream.getTracks().forEach(track => {
            track.stop();
        });

    }

    function start() {

    }

    function stop() {
    }

    //连接发生错误的回调方法
    ws.onerror = function () {
    };

    //连接成功建立的回调方法
    ws.onopen = function (event) {
        console.log('websocket 连接成功！')
    }

    //接收到消息的回调方法
    ws.onmessage = function (event) {
        console.log(event.data)
    }

    //连接关闭的回调方法
    ws.onclose = function () {
        console.log('websocket连接关闭！')
        // 3秒后重新连接
        setTimeout(function () {
            console.log('开始重新连接')
            connectWebSocket()
        }, 2000)
    }


</script>
</body>
</html>